package com.ns.dcjh.listener;

import static com.ns.dcjh.utils.FileUtils.isExist;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.hht.webpackagekit.core.Constants;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.ns.dcjh.BuildConfig;
import com.ns.dcjh.MyApplication;
import com.ns.dcjh.R;
import com.ns.dcjh.bean.APPResponseToWebBean;
import com.ns.dcjh.bean.JpushIDBean;
import com.ns.dcjh.bean.MessageEvent;
import com.ns.dcjh.bean.StatusBarBean;
import com.ns.dcjh.constant.Constant;
import com.ns.dcjh.ui.activity.FullScreenActivity;
import com.ns.dcjh.ui.activity.MyScanActivity;
import com.ns.dcjh.ui.activity.VideoPalyActivity;
import com.ns.dcjh.utils.BitmapUtils;
import com.ns.dcjh.utils.BlockUtils;
import com.ns.dcjh.utils.ClipboardUtils;
import com.ns.dcjh.utils.DeviceIdUtil;
import com.ns.dcjh.utils.DouYinUtils;
import com.ns.dcjh.utils.FileUtils;
import com.ns.dcjh.utils.HelperUtils;
import com.ns.dcjh.utils.KuaiShouUtils;
import com.ns.dcjh.utils.LoadingUtils;
import com.ns.dcjh.utils.ShareUtils;
import com.ns.dcjh.utils.SharedPreferencesUtils;
import com.ns.dcjh.utils.StatusBarUtils;
import com.ns.dcjh.utils.ToastUtils;
import com.ns.dcjh.utils.WebviewPickerUtils;
import com.ns.dcjh.utils.XiaoHongShuUtils;
import com.ns.dcjh.utils.upyun.UpYunCompleteListener;
import com.ns.dcjh.utils.upyun.UpYunEntity;
import com.ns.dcjh.utils.upyun.UpYunUtil;
import com.ns.dcjh.vo.AppRespVo;
import com.ns.dcjh.vo.ClientInfoRespVo;
import com.ns.dcjh.vo.ClientInfoVo;
import com.ns.dcjh.vo.DouYinVideoInfoVo;
import com.ns.dcjh.vo.KuaiShouInfoVo;
import com.ns.dcjh.vo.RegIdLoginRespVo;
import com.ns.dcjh.vo.SignBaseVo;
import com.ns.dcjh.vo.WxLoginRespVo;
import com.ns.dcjh.vo.WxUserInfoVo;
import com.ns.dcjh.vo.XiaoHongShuVo;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yxing.ScanCodeConfig;
import com.yxing.def.ScanStyle;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.jpush.android.helper.JCoreHelper;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


public class JSInterfaceHolderListener {
    private JSONObject jsData;
    private WebView webView;
    private final Context mContext;
    private String action = "";
    public final MyUMShareListener umShareListener = new MyUMShareListener();
    private boolean upVideoFlag = false;
    private String uploadType;

    public final UpYunUtil upYunUtil = new UpYunUtil();

    public JSInterfaceHolderListener(Context mContext, WebView webView) {
        this.mContext = mContext;
        this.webView = webView;

        umShareListener.setOnSuccess(new BlockUtils() {
            @Override
            public void callbackWithBoolean(Boolean data, String errorMsg) {
                JSONObject userData = jsData.getJSONObject("user_data");
                AppRespVo vo = new AppRespVo();
                vo.setAction(action);
                vo.setUser_data(userData);
                vo.setStatus(data);

                sendResponse(JSONObject.toJSONString(vo));
                ToastUtils.info(mContext, "分享成功");
            }
        });
        umShareListener.setOnError(new BlockUtils() {
            @Override
            public void callbackWithBoolean(Boolean data, String errorMsg) {
                JSONObject userData = jsData.getJSONObject("user_data");
                AppRespVo vo = new AppRespVo();
                vo.setUser_data(userData);
                vo.setAction(action);
                vo.setMessage("分享失败");
                vo.setStatus(data);

                sendResponse(JSONObject.toJSONString(vo));
                ToastUtils.info(mContext, "分享失败==>" + errorMsg);
            }
        });

    }

    @JavascriptInterface
    public synchronized void postMessage(String json) {
        jsData = JSONObject.parseObject(json);
        String action = jsData.getString("action");
        Log.e("JS", String.format("WebView On Post Message: %s", json));
        this.action = action;
        try {
            handleAction();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isAction(String action) {
        return StringUtils.equals(this.action, action);
    }

    //处理Action
    private synchronized void handleAction() {
        String params = null;
        if (isAction("get_client")) {
            //获取客户端信息
            params = getClient();
        } else if (isAction("url")) {
            //是否首页
            url();
        } else if (isAction("clear_cache")) {
            //清除缓存
            clearCache();
        } else if (isAction("clear_cookie")) {
            //清除cookie
            clearCookie();
        } else if (isAction("wc_login")) {
            //微信登录
            wxLogin();
        } else if (isAction("reg_id_login")) {
            //登录
            params = regIdLogin();
        } else if (isAction("set_boot_img")) {
            //设置启动图
            setSplashImage();
        } else if (isAction("copy_text")) {
            //复制文字
            params = copyText();
        } else if (isAction("friend_img")) {
            //分享好友图片
//            checkCanAccessStorage(new BlockUtils() {
//                @Override
//                public void callback() {
//                    shareWxImage(SHARE_MEDIA.WEIXIN);
//                }
//            });
            shareWxImage(SHARE_MEDIA.WEIXIN);
        } else if (isAction("friend_link")) {
            //分享好友链接
            shareWxLink(SHARE_MEDIA.WEIXIN);
        } else if (isAction("moments_link")) {
            //分享链接至朋友圈
            shareWxLink(SHARE_MEDIA.WEIXIN_CIRCLE);
        } else if (isAction("moments_img")) {
            //分享朋友圈照片
//            checkCanAccessStorage(new BlockUtils() {
//                @Override
//                public void callback() {
//                    shareWxImage(SHARE_MEDIA.WEIXIN_CIRCLE);
//                }
//            });
            shareWxImage(SHARE_MEDIA.WEIXIN_CIRCLE);
        } else if (isAction("friend_card")) {
            //分享好友卡片
            shareFriendCard(SHARE_MEDIA.WEIXIN);
        } else if (isAction("goto_mnp")) {
            //打开微信小程序
            openWxMp();
        } else if (isAction("location")) {
            //获取定位信息
            getLocation();
        } else if (isAction("upgrade")) {
            //升级更新
            appUpgrade();
        } else if (isAction("open_douyin")) {
            //打开抖音
            openDouYin();
        } else if (isAction("open_small_red_book")) {
            // 打开小红书
            openXiaoHongShu();
        } else if (isAction("saveImage")) {
            //保存图片
            saveImage();
        } else if (isAction("download_poster")) {
            //下载海报
            downloadPoster();
        } else if (isAction("prompt")) {
            //提词器
            showPrompt();
        } else if (isAction("get_clipboard")) {
            //获取剪切板第一条数据
            getClipboardText();
        } else if (isAction("goto_browser")) {
            gotoBrowser();
        } else if (isAction("douyin_code")) {
            douyinAuth();
        } else if (isAction("open_kuaishou")) {
            openKuaiShou();
        } else if (isAction("scan_code")) {
            //扫码
            checkCanAccessCamera(new BlockUtils() {
                @Override
                public void callback() {
                    ScanCodeConfig.create((Activity) mContext)
                            //设置扫码页样式 ScanStyle.NONE：无  ScanStyle.QQ ：仿QQ样式   ScanStyle.WECHAT ：仿微信样式
                            .setStyle(ScanStyle.WECHAT)
                            //扫码成功是否播放音效  true ： 播放   false ： 不播放
                            .setPlayAudio(true)
                            .buidler()
                            //跳转扫码页   扫码页可自定义样式
                            .start(MyScanActivity.class);
                }
            });
        } else if (isAction("custom_notice_open")) {
//            openNotification();
        } else if (isAction("vibrate")) {
            vibrate();
        } else if (isAction("call_number")) {
            //打电话
            callPhone();
        } else if (isAction("get_device_info")) {
            //获取设备信息
            getDeviceInfo();
        } else if (isAction("web_reload")) {
            //重新加载网页
            reloadWeb();
        } else if (isAction("web_loaded")) {
            //网页已经加载通知
            loadedNotify();
        } else if (isAction("video_upload")) {
            //选取视频
            JSONObject data = jsData;
            ((Activity) mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                            if (upVideoFlag) return;
                    if (isAction("video_upload")) {
                        uploadType = jsData.getJSONObject("params").getString("upload_type");
                        videoPick(data);
                    }
                }
            });
        } else if (isAction("video_upload_cancel")) {
            //取消上传
            cancelVideoUpload();
        } else if (isAction("play_video_error")) {
            if (jsData.getJSONObject("params") != null) {
                String url = jsData.getJSONObject("params").getString("url");
                if (url != null && !url.isEmpty()) {
                    startUrlVideo(url);
                }
            }
        } else if (isAction("get_bar_height")) {
            getBarHeightAndSend();
        } else if (isAction("set_status_bar_style")) {
            setStatusBarStyle();
        } else if (isAction("get_offline_package")) {
            getOfflinePackage();
        } else if (isAction("delete_files")) {
            deleteFile();
        } else if (isAction("wx_get_user_info")) {
            //微信登录
            wxLogin(jsData.getJSONObject("params").getString("functionName"));
        } else if (isAction("get_jpush_reg_id")) {
            //微信登录
            getJpushID(jsData.getJSONObject("params").getString("functionName"));
        }
        if (StringUtils.isNotEmpty(params)) {
            sendResponse(params);
        }
    }

    //获取client信息
    private String getClient() {
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);

        ClientInfoRespVo clientInfoRespVo = new ClientInfoRespVo();
        clientInfoRespVo.setAction(this.action);

        ClientInfoVo clientInfoVo = new ClientInfoVo();
        clientInfoVo.setWidth(dm.widthPixels);
        clientInfoVo.setHeight(dm.heightPixels);
        clientInfoVo.setVersion(BuildConfig.VERSION_NAME);
        clientInfoVo.setRole("agent");
        clientInfoVo.setBrand(Build.BRAND);
        clientInfoVo.setModel(Build.MODEL);

        List<String> versionArr = Arrays.asList(clientInfoVo.getVersion().split("\\."));
        if (versionArr.size() == 3) {
            int code = Integer.parseInt(versionArr.get(0)) << 24 | Integer.parseInt(versionArr.get(1)) << 16 | Integer.parseInt(versionArr.get(2));
            clientInfoVo.setCode(code);
        }
        clientInfoRespVo.setResult(clientInfoVo);

        return JSONObject.toJSONString(clientInfoRespVo);
    }

    //是否首页
    private void url() {
        JSONObject extras = new JSONObject();
        extras.put("isHome", jsData.getJSONObject("params") == null || jsData.getJSONObject("params").getBooleanValue("is_index"));
        MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_URL_IS_HOME);
        msgEvent.setExtras(extras);
        EventBus.getDefault().post(msgEvent);
    }

    //清除缓存
    private void clearCache() {
        if (webView == null) return;

        //必须放在UIThread中操作，否则会崩溃
        ((Activity) mContext).runOnUiThread(new Thread() {
            @Override
            public void run() {
                webView.clearCache(true);
                AppRespVo vo = new AppRespVo();
                vo.setAction(action);
                vo.setUser_data(jsData.getJSONObject("user_data"));
                vo.setMessage("清除成功");
                sendResponse(JSONObject.toJSONString(vo));
            }
        });
    }

    private void clearCookie() {
        if (webView == null) return;

        //必须放在UIThread中操作，否则会崩溃
        ((Activity) mContext).runOnUiThread(new Thread() {
            @Override
            public void run() {
                SharedPreferencesUtils.getInstance(mContext).removeObjectForKey("cookie");
                CookieManager cookieManager = CookieManager.getInstance();
                cookieManager.removeAllCookie();
                AppRespVo vo = new AppRespVo();
                vo.setAction(action);
                vo.setUser_data(jsData.getJSONObject("user_data"));
                vo.setMessage("清除成功");
                sendResponse(JSONObject.toJSONString(vo));
            }
        });
    }

    //重新加载网页
    private void reloadWeb() {
        if (webView == null) return;

        //必须放在UIThread中操作，否则会崩溃
        ((Activity) mContext).runOnUiThread(new Thread() {
            @Override
            public void run() {
                webView.clearCache(true);
                webView.reload();
                AppRespVo vo = new AppRespVo();
                vo.setAction(action);
                vo.setUser_data(jsData.getJSONObject("user_data"));
                vo.setMessage("重新加载");
                sendResponse(JSONObject.toJSONString(vo));
            }
        });
    }

    private void loadedNotify() {
        MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_LOADED_NOTIFY);
        msgEvent.setExtras(jsData);
        EventBus.getDefault().post(msgEvent);
    }

    //微信登录
    private void wxLogin() {
        MyUMAuthListener umAuthListener = new MyUMAuthListener(mContext);
        umAuthListener.setOnError(new BlockUtils() {
            @Override
            public void callbackWithJSONObject(JSONObject data) {
                RegIdLoginRespVo vo = new RegIdLoginRespVo();
                vo.setAction("wc_login");
                vo.setStatus(false);
                String msg = "微信授权失败";
                switch (data.getIntValue("action")) {
                    case -1:
                        msg = "您的手机未安装微信";
                        break;
                    case -7:
                        msg = "登录错误, 请重试";
                        break;
                    case -8:
                        msg = "获取用户信息失败";
                        break;
                }
                vo.setMessage(msg);
                sendResponse(JSONObject.toJSONString(vo));
            }
        });

        umAuthListener.setOnSuccess(new BlockUtils() {
            @Override
            public void callbackWithJSONObject(JSONObject data) {

                SharedPreferencesUtils sp = SharedPreferencesUtils.getInstance(mContext);
                String regId = String.valueOf(sp.objectForKey(Constant.SP_KEY_REGISTRATION_ID, ""));

                WxLoginRespVo vo = new WxLoginRespVo();
                vo.setAction("wc_login");

                WxUserInfoVo userInfoVo = new WxUserInfoVo();

                String timestamp = jsData.getJSONObject("params") != null ? jsData.getJSONObject("params").getString("timestamp") : String.valueOf(System.currentTimeMillis() / 1000);
                userInfoVo.setTimestamp(timestamp);
                userInfoVo.setJg_reg_id(regId);
                userInfoVo.setNonce(HelperUtils.getRandomString(16));


                userInfoVo.setUnionid(data.getString("unionid"));
                userInfoVo.setOpenid(data.getString("openid"));
                userInfoVo.setNickname(data.getString("name"));
                userInfoVo.setHeadimgurl(data.getString("profile_image_url"));
                userInfoVo.setSex(data.getString("gender"));

                ArrayList<String> signArr = new ArrayList<>();
                signArr.add(userInfoVo.getClient());
                signArr.add(userInfoVo.getUnionid());
                signArr.add(userInfoVo.getJg_reg_id());
                signArr.add(userInfoVo.getTimestamp());
                signArr.add(userInfoVo.getNonce());
                signArr.add(Constant.JS_SIGN_KEY);

                userInfoVo.setSignature(HelperUtils.createSignature(signArr));

                vo.setResult(userInfoVo);
                sendResponse(JSONObject.toJSONString(vo));
            }
        });

        try {
            UMShareConfig config = new UMShareConfig();
            config.isNeedAuthOnGetUserInfo(true);
            UMShareAPI api = UMShareAPI.get(mContext);
            api.setShareConfig(config);
            api.getPlatformInfo((Activity) mContext, SHARE_MEDIA.WEIXIN, umAuthListener);
        } catch (Exception e) {
            ToastUtils.info(mContext, "登录失败，请重试");
        }
    }

    //微信登录
    private void wxLogin(String functionName) {
        MyUMAuthListener umAuthListener = new MyUMAuthListener(mContext);
        umAuthListener.setOnError(new BlockUtils() {
            @Override
            public void callbackWithJSONObject(JSONObject data) {
                String msg = "微信授权失败";
                switch (data.getIntValue("action")) {
                    case -1:
                        msg = "您的手机未安装微信";
                        break;
                    case -7:
                        msg = "登录错误, 请重试";
                        break;
                    case -8:
                        msg = "获取用户信息失败";
                        break;
                }
                APPResponseToWebBean<RegIdLoginRespVo> vo = new APPResponseToWebBean<>(0, null, msg, functionName);
                sendResponse(functionName, new Gson().toJson(vo));
            }
        });

        umAuthListener.setOnSuccess(new BlockUtils() {
            @Override
            public void callbackWithJSONObject(JSONObject data) {

                SharedPreferencesUtils sp = SharedPreferencesUtils.getInstance(mContext);
                String regId = String.valueOf(sp.objectForKey(Constant.SP_KEY_REGISTRATION_ID, ""));

                WxUserInfoVo userInfoVo = new WxUserInfoVo();

                String timestamp = jsData.getJSONObject("params") != null ? jsData.getJSONObject("params").getString("timestamp") : String.valueOf(System.currentTimeMillis() / 1000);
                userInfoVo.setTimestamp(timestamp);
                userInfoVo.setJg_reg_id(regId);
                userInfoVo.setNonce(HelperUtils.getRandomString(16));


                userInfoVo.setUnionid(data.getString("unionid"));
                userInfoVo.setOpenid(data.getString("openid"));
                userInfoVo.setNickname(data.getString("name"));
                userInfoVo.setHeadimgurl(data.getString("profile_image_url"));
                userInfoVo.setSex(data.getString("gender"));

                ArrayList<String> signArr = new ArrayList<>();
                signArr.add(userInfoVo.getClient());
                signArr.add(userInfoVo.getUnionid());
                signArr.add(userInfoVo.getJg_reg_id());
                signArr.add(userInfoVo.getTimestamp());
                signArr.add(userInfoVo.getNonce());
                signArr.add(Constant.JS_SIGN_KEY);

                userInfoVo.setSignature(HelperUtils.createSignature(signArr));

                APPResponseToWebBean<WxUserInfoVo> vo = new APPResponseToWebBean<>(0, userInfoVo, "success", functionName);
                sendResponse(functionName, new Gson().toJson(vo));
            }
        });

        try {
            UMShareConfig config = new UMShareConfig();
            config.isNeedAuthOnGetUserInfo(true);
            UMShareAPI api = UMShareAPI.get(mContext);
            api.setShareConfig(config);
            api.getPlatformInfo((Activity) mContext, SHARE_MEDIA.WEIXIN, umAuthListener);
        } catch (Exception e) {
            ToastUtils.info(mContext, "登录失败，请重试");
        }
    }

    //登录
    private String regIdLogin() {
        SharedPreferencesUtils sp = SharedPreferencesUtils.getInstance(mContext);
        String regId = String.valueOf(sp.objectForKey(Constant.SP_KEY_REGISTRATION_ID, ""));

        RegIdLoginRespVo vo = new RegIdLoginRespVo();
        vo.setAction(this.action);
        SignBaseVo signBaseVo = new SignBaseVo();
        String timestamp = jsData.getJSONObject("params") != null ? jsData.getJSONObject("params").getString("timestamp") : String.valueOf(System.currentTimeMillis() / 1000);
        signBaseVo.setTimestamp(timestamp);
        signBaseVo.setJg_reg_id(regId);
        signBaseVo.setNonce(HelperUtils.getRandomString(16));

        ArrayList<String> signArr = new ArrayList<>();
        signArr.add(signBaseVo.getClient());
        signArr.add("");
        signArr.add(signBaseVo.getJg_reg_id());
        signArr.add(signBaseVo.getTimestamp());
        signArr.add(signBaseVo.getNonce());
        signArr.add(Constant.JS_SIGN_KEY);

        signBaseVo.setSignature(HelperUtils.createSignature(signArr));
        vo.setResult(signBaseVo);

        return JSONObject.toJSONString(vo);
    }

    private void getJpushID(String functionName) {
        SharedPreferencesUtils sp = SharedPreferencesUtils.getInstance(mContext);
        String regId = String.valueOf(sp.objectForKey(Constant.SP_KEY_REGISTRATION_ID, ""));
        APPResponseToWebBean<JpushIDBean> vo = new APPResponseToWebBean<>(0, new JpushIDBean(regId), "success", functionName);
        sendResponse(functionName, new Gson().toJson(vo));
    }

    //设置启动图
    private void setSplashImage() {
        JSONObject params = jsData.getJSONObject("params");
        String url = params.getString("url");
        Long duration = params.getLongValue("duration");
        SharedPreferencesUtils sp = SharedPreferencesUtils.getInstance(mContext);

        AppRespVo vo = new AppRespVo();
        vo.setAction(action);
        JSONObject result = new JSONObject();

        String oldUrl = sp.objectForKey(Constant.SP_KEY_SPLASH_URL, "").toString();

        if (StringUtils.isEmpty(url)) {
            //为空清除缓存
            sp.removeObjectForKey(Constant.SP_KEY_SPLASH_URL);
            sp.removeObjectForKey(Constant.SP_KEY_SPLASH_IMG);
            sp.removeObjectForKey(Constant.SP_KEY_SPLASH_DURATION);
            vo.setMessage("启动图缓存已清除");
            result.put("old_url", oldUrl);
            result.put("new_url", "");
            vo.setResult(result);
            sendResponse(JSONObject.toJSONString(vo));
            return;
        }


        if (StringUtils.equals(url, oldUrl)) {
            //地址相同不缓存
            result.put("old_url", oldUrl);
            result.put("new_url", url);
            vo.setResult(result);
            sendResponse(JSONObject.toJSONString(vo));
        } else {
            Glide.with(mContext)
                    .asBitmap()
                    .load(url)
                    .into(new CustomTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            sp.setObject(Constant.SP_KEY_SPLASH_URL, url);
                            sp.setObject(Constant.SP_KEY_SPLASH_IMG, BitmapUtils.bitmapToBase64(resource, mContext));
                            sp.setObject(Constant.SP_KEY_SPLASH_DURATION, duration);


                            result.put("old_url", oldUrl);
                            result.put("new_url", url);
                            vo.setResult(result);
                            sendResponse(JSONObject.toJSONString(vo));
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {

                        }

                        @Override
                        public void onLoadFailed(@Nullable Drawable errorDrawable) {
                            super.onLoadFailed(errorDrawable);

                            result.put("old_url", oldUrl);
                            result.put("new_url", url);
                            vo.setResult(result);
                            vo.setStatus(false);
                            vo.setMessage("缓存图片出现异常");
                            sendResponse(JSONObject.toJSONString(vo));
                        }
                    });
        }

    }

    //复制文本
    private String copyText() {
        try {
            String txt = jsData.getJSONObject("params").getString("copy_text");
            ClipboardUtils.setText(mContext, txt);
        } catch (Exception e) {
            e.printStackTrace();
        }

        AppRespVo vo = new AppRespVo();
        vo.setAction(this.action);
        vo.setStatus(true);

        return JSONObject.toJSONString(vo);
    }

    private void getBarHeightAndSend() {
        String functionName = jsData.getJSONObject("params").getString("functionName");
        int height = pxToDp(mContext, StatusBarUtils.getStatusBarHeight((Activity) mContext));
        APPResponseToWebBean<StatusBarBean> appResponse =
                new APPResponseToWebBean<StatusBarBean>(0, new StatusBarBean(height), "success", functionName);
        sendResponse(functionName, new Gson().toJson(appResponse));
    }

    private void getOfflinePackage() {
        String package_url = jsData.getJSONObject("params").getString("package_url");
        if (package_url.isEmpty()) {
            package_url = Constants.BASE_PACKAGE_INDEX;
        }
        JSONObject extras = new JSONObject();
        extras.put("package_url", package_url);
        MessageEvent msgEvent = new MessageEvent(Constant.MSG_OFFLINE_PACKAGE_DOWNLOAD);
        msgEvent.setExtras(extras);
        EventBus.getDefault().post(msgEvent);
    }

    public void returnOfflineResult(String result) {
        String functionName = "offline_package_func";
        APPResponseToWebBean<?> appResponse = null;
        if ("success".equals(result)) {
            appResponse =
                    new APPResponseToWebBean<>(0, null, "success", functionName);
        } else {
            appResponse =

                    new APPResponseToWebBean<>(1, null, "failed", functionName);
        }
        sendResponse(functionName, new Gson().toJson(appResponse));
    }

    private void deleteFile() {
        String functionName = jsData.getJSONObject("params").getString("functionName");
        List<String> filePathList = jsData.getJSONObject("params").getObject("file_path_list", List.class);
        for (String filePath : filePathList) {
            String sufiix = filePath.substring(filePath.lastIndexOf('.') + 1);
            if (Build.VERSION.SDK_INT > 29 && ("png".equals(sufiix) || "jpg".equals(sufiix))) {
                BitmapUtils.deleteImageByFileName(mContext, filePath);
            } else if (Build.VERSION.SDK_INT > 29 && ("mp4".equals(sufiix))) {
                BitmapUtils.deleteVideoByFileName(mContext, filePath);
            } else {
                File file = new File(filePath);
                file.delete();
            }
        }
        APPResponseToWebBean<Object> appResponse =
                new APPResponseToWebBean<>(0, null, "success", functionName);
        sendResponse(functionName, new Gson().toJson(appResponse));
    }

    private int pxToDp(Context context, int px) {
        float density = context.getResources().getDisplayMetrics().density;
        return Math.round(px / density);
    }

    private void setStatusBarStyle() {
        String functionName = jsData.getJSONObject("params").getString("functionName");
        String statusBarStyleBackgoundColor = jsData.getJSONObject("params").getString("statusBarStyleBackgoundColor");
        String statusBarStyleTextColor = jsData.getJSONObject("params").getString("statusBarStyleTextColor");

        JSONObject extras = new JSONObject();
        extras.put("statusBarStyleBackgoundColor", statusBarStyleBackgoundColor);
        extras.put("statusBarStyleTextColor", statusBarStyleTextColor);
        MessageEvent msgEvent = new MessageEvent(Constant.STATUS_UI_UPDATE);
        msgEvent.setExtras(extras);
        EventBus.getDefault().post(msgEvent);
        APPResponseToWebBean<Object> appResponse =
                new APPResponseToWebBean<>(0, null, "success", functionName);
        sendResponse(functionName, new Gson().toJson(appResponse));
    }

    //分享微信图片
    private void shareWxImage(SHARE_MEDIA platform) {
        String txt = jsData.getJSONObject("params").getString("copy_text");
        String imgContent = jsData.getJSONObject("params").getString("img_content");
//        String imgContent = readFileFromAssets(mContext, "base64.txt");
        String[] imgContentSplit = imgContent.split(",");
        Toast.makeText(mContext, "正在调起微信进行分享", Toast.LENGTH_SHORT).show();
        ClipboardUtils.setText(mContext, txt);

        try {
            Bitmap bitmap = BitmapUtils.base64ToBitmap(imgContentSplit[1], mContext);
            if (bitmap != null) {
                Log.e("shareWxImage", "图片不为null，开始压缩图片");
                byte[] compressByte = compressBitmapToFit(bitmap);
                if (compressByte == null) {
                    ToastUtils.info(mContext, "分享失败, 可能图片太大了");
                    return;
                }
                Log.e("shareWxImage", "压缩图片成功，开始分享");
                ShareUtils.shareWxImageWithBitmap(mContext, platform, compressByte);
            } else {
                Log.e("shareWxImage", "图片为null");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("shareWxImage", e.toString());
            ToastUtils.info(mContext, "分享失败, 可能图片太大了");
        }

//        ShareUtils.shareWxImageWithBitmapByUmeng(mContext, platform, BitmapUtils.base64ToBitmap(imgContentSplit[1]),umShareListener);

    }

    public static String readFileFromAssets(Context context, String fileName) {
        String result = "";
        try {
            InputStream inputStream = context.getAssets().open(fileName);
            int size = inputStream.available();
            byte[] buffer = new byte[size];
            inputStream.read(buffer);
            inputStream.close();
            result = new String(buffer, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static byte[] compressBitmapToFit(Bitmap bitmap) {
        int quality = 100;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG;

        do {
            baos.reset();
            bitmap.compress(format, quality, baos);
            byte[] bytes = baos.toByteArray();

            if (bytes.length <= 1024 * 1024 / 3) {
                return bytes;
            }

            quality -= 5;
        } while (quality > 0);

        // 如果经过多次尝试仍无法压缩到 500KB 以下，可以考虑采取其他策略，如降低分辨率等。
        return null;
    }


    //分享微信朋友圈链接
    private void shareWxLink(SHARE_MEDIA platform) {
        JSONObject params = jsData.getJSONObject("params");
        if (params == null) return;
        Toast.makeText(mContext, "正在调起微信进行分享", Toast.LENGTH_SHORT).show();
        String txt = params.getString("copy_text");
        ClipboardUtils.setText(mContext, txt);

        Bitmap image = BitmapUtils.getBitmapForUrlOrBase64(mContext, params.getString("img_path"));

        ShareUtils.shareWeb(
                mContext,
                platform.equals(SHARE_MEDIA.WEIXIN),
                params.getString("title"),
                params.getString("description"),
                params.getString("link"),
                image
        );
    }

    //分享好友卡片
    private void shareFriendCard(SHARE_MEDIA platform) {
        JSONObject params = jsData.getJSONObject("params");
        if (params == null) return;

        Toast.makeText(mContext, "正在调起微信进行分享", Toast.LENGTH_SHORT).show();
        String txt = params.getString("copy_text");
        ClipboardUtils.setText(mContext, txt);

        Bitmap image = BitmapUtils.getBitmapForUrlOrBase64(mContext, params.getString("img_path"));

        ShareUtils.shareMiniProgram(
                mContext,
                params.getString("title"),
                params.getString("userName"),
                params.getString("link"),
                image
        );
    }


    //打开微信小程序
    public void openWxMp() {
        JSONObject params = jsData.getJSONObject("params");
        String appId = StringUtils.isEmpty(params.getString("appId")) ? Constant.WECHAT_APP_ID : params.getString("appId");
        String userName = StringUtils.isEmpty(params.getString("userName")) ? Constant.WECHAT_MP_ID : params.getString("userName");
        String path = params.getString("path");
        String mnpType = params.getString("mnp_type");
        int type = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;
        if (StringUtils.equals(mnpType, "experience")) {
            type = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW;
        } else if (StringUtils.equals(mnpType, "develop")) {
            type = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_TEST;
        }

        IWXAPI iwxapi = WXAPIFactory.createWXAPI(mContext, appId);
        WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
        req.userName = userName;
        req.path = path;
        req.miniprogramType = type;
        iwxapi.sendReq(req);
    }

    //获取定位信息
    private void getLocation() {
        MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_GET_LOCATION);
        msgEvent.setExtras(jsData);
        EventBus.getDefault().post(msgEvent);
    }

    //发送小程序信息
    public void sendMpResp(JSONObject data) {
        JSONObject userData = jsData.getJSONObject("user_data");
        AppRespVo vo = new AppRespVo();
        vo.setAction(action);
        vo.setUser_data(userData);
        vo.setResult(data);

        sendResponse(JSONObject.toJSONString(vo));
    }

    //抖音分享回调
    public void sendDyResp(JSONObject data) {
        if (data.getIntValue("errorCode") == 0) {
            showToast("分享成功");
        } else {
            showToast(data.getString("errorMsg"));
        }
    }

    //消息回调
    public void sendMsgResp(JSONObject data) {
        sendResponse(data.toJSONString());
    }

    //发送定位获取失败的信息
    public void sendLocationFailResp(JSONObject data) {
        try {
            JSONObject userData = data.getJSONObject("user_data");
            AppRespVo vo = new AppRespVo();
            vo.setAction(data.getString("action"));
            vo.setUser_data(userData);
            vo.setStatus(false);
            vo.setMessage("请开启定位权限");

            sendResponse(JSONObject.toJSONString(vo));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送定位获取成功的信息
    public void sendLocationSuccessResp(JSONObject data, JSONObject userData) {
        AppRespVo vo = new AppRespVo();
        vo.setUser_data(userData.getJSONObject("user_data"));
        vo.setAction(userData.getString("action"));
        vo.setResult(data);
        sendResponse(JSONObject.toJSONString(vo));
    }

    //发送存储访问权限失败的信息
    public void sendStorageAccessFailResp(JSONObject data) {
        try {
            JSONObject userData = data.getJSONObject("user_data");
            AppRespVo vo = new AppRespVo();
            vo.setAction(data.getString("action"));
            vo.setUser_data(userData);
            vo.setStatus(false);
            vo.setMessage("请开启存储访问权限");

            sendResponse(JSONObject.toJSONString(vo));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送存储访问权限失败的信息
    public void sendCameraFailResp(JSONObject data) {
        try {
            JSONObject userData = data.getJSONObject("user_data");
            AppRespVo vo = new AppRespVo();
            vo.setAction(data.getString("action"));
            vo.setUser_data(userData);
            vo.setStatus(false);
            vo.setMessage("请开启相机访问权限");

            sendResponse(JSONObject.toJSONString(vo));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //APP更新
    private void appUpgrade() {
        JSONObject params = jsData.getJSONObject("params");
        JSONObject extras = new JSONObject();
        extras.put("url", params.getString("url"));
        extras.put("force", params.getBooleanValue("force"));
        extras.put("description", params.getString("description"));
        MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_APP_UPGRADE);
        msgEvent.setExtras(extras);
        EventBus.getDefault().post(msgEvent);
    }

    public void showToast(String message) {
        ((Activity) mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.info(mContext, message);
            }
        });
    }

    //打开抖音
    private void openDouYin() {
        //检测是否安装了抖音
        if (!DouYinUtils.isInstalled(mContext)) {
            showToast("该手机未检测到安装了抖音短视频App");
            return;
        }

        JSONObject params = jsData.getJSONObject("params");
        ClipboardUtils.setText(mContext, params.getString("text"));

        DouYinVideoInfoVo vo = new DouYinVideoInfoVo();
        vo.setTag(params.getString("tag"));
        vo.setVideo(params.getString("video"));
        vo.setUseImgs(params.getBooleanValue("use_imgs"));
        if (vo.isUseImgs()) {
            vo.setImgs(params.getJSONArray("base64_imgs"));
        } else {
            vo.setVideoNb(params.getString("video_nb"));
        }

        DouYinUtils douYinUtils = new DouYinUtils(mContext);
        douYinUtils.share(vo);
    }

    //打开小红书
    private void openXiaoHongShu() {
        //检测是否安装了抖音
        if (!XiaoHongShuUtils.isInstalled(mContext)) {
            JSONObject userData = jsData.getJSONObject("user_data");
            AppRespVo vo = new AppRespVo();
            vo.setAction(action);
            vo.setUser_data(userData);
            vo.setMessage("该手机未检测到安装了小红书");
            vo.setStatus(false);

            sendResponse(JSONObject.toJSONString(vo));
            return;
        }

        JSONObject params = jsData.getJSONObject("params");
        ClipboardUtils.setText(mContext, params.getString("text"));

        XiaoHongShuVo vo = new XiaoHongShuVo();
        vo.setTitle(params.getString("tag"));
        vo.setContent(params.getString("text"));
        if (params.getBooleanValue("use_imgs")) {
            JSONArray base64_imgs = params.getJSONArray("base64_imgs");
            List<String> pathlist = new ArrayList<>();
            for (int i = 0; i < base64_imgs.size(); i++) {
                try {
                    pathlist.add(base64_imgs.getString(i));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            vo.setImgPath(pathlist);
        }
        if (params.getString("video") != null) {
            vo.setVideoPath(params.getString("video"));
        }
        if (params.getString("video_nb") != null) {
            vo.setVideoNBPath(params.getString("video_nb"));
        }
        XiaoHongShuUtils xiaoHongShuUtils = new XiaoHongShuUtils(mContext);
        xiaoHongShuUtils.share(vo);
    }

    /**
     * 保存图片
     */
    private void saveImage() {
        JSONObject params = jsData.getJSONObject("params");
        AppRespVo vo = new AppRespVo();
        vo.setAction(this.action);
        vo.setUser_data(jsData.getJSONObject("user_data"));

        String file = params.getString("filePath");
        Bitmap bitmap = BitmapUtils.getBitmapForUrlOrBase64(mContext, file);
        Observable<File> observable;
        if (Build.VERSION.SDK_INT > 29) {
            observable = BitmapUtils.bitmapSaveFileToGallery(mContext, bitmap);
        } else {
            observable = BitmapUtils.bitmapSaveFileToStorage(bitmap);
        }

        observable.subscribe(new Observer<File>() {
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull File file) {
                vo.setStatus(true);
                vo.setMessage("已成功下载至图库");
                sendResponse(JSONObject.toJSONString(vo));
                if (Build.VERSION.SDK_INT <= 29) {
                    mediaReload(file);
                }
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                vo.setStatus(false);
                vo.setMessage("保存失败");
                sendResponse(JSONObject.toJSONString(vo));
            }

            @Override
            public void onComplete() {

            }
        });
    }

    //下载海报
    private void downloadPoster() {
        JSONObject params = jsData.getJSONObject("params");
        String type = params.getString("type");
        String source = params.getString("source");

        AppRespVo vo = new AppRespVo();
        vo.setAction(this.action);
        vo.setUser_data(jsData.getJSONObject("user_data"));

        if (StringUtils.isEmpty(source)) {
            vo.setStatus(false);
            vo.setMessage("下载目标数据为空，请重试");
            sendResponse(JSONObject.toJSONString(vo));
            return;
        }

        if (StringUtils.equals(type, Constant.DOWNLOAD_POSTER_TYPE_IMAGE)) {
            //下载图片
            Bitmap bitmap = BitmapUtils.getBitmapForUrlOrBase64(mContext, source);
            Observable<File> observable;
            if (Build.VERSION.SDK_INT > 29) {
                observable = BitmapUtils.bitmapSaveFileToGallery(mContext, bitmap);
            } else {
                observable = BitmapUtils.bitmapSaveFileToStorage(bitmap);
            }
            observable.subscribe(new Observer<File>() {
                @Override
                public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

                }

                @Override
                public void onNext(@io.reactivex.annotations.NonNull File file) {
                    vo.setStatus(true);
                    vo.setMessage("已成功下载至相册");
                    JSONObject result = new JSONObject();
                    result.put("file_path", file.getPath());
                    vo.setResult(result);
                    sendResponse(JSONObject.toJSONString(vo));
                    if (Build.VERSION.SDK_INT <= 29) {
                        mediaReload(file);
                    }
                }

                @Override
                public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                    vo.setStatus(false);
                    vo.setMessage("下载失败");
                    sendResponse(JSONObject.toJSONString(vo));
                }

                @Override
                public void onComplete() {

                }
            });
        } else if (StringUtils.equals(type, Constant.DOWNLOAD_POSTER_TYPE_VIDEO)) {
            //下载视频
            File file = FileUtils.getFile("video", "mp4");

            LoadingUtils mLoading = LoadingUtils.create(mContext).show();
            FileDownloader
                    .getImpl()
                    .create(source)
                    .setPath(file.getAbsolutePath())
                    .setListener(new FileDownloadListener() {
                        @Override
                        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                        }

                        @Override
                        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                        }

                        @Override
                        protected void completed(BaseDownloadTask task) {
                            mLoading.dismiss();
                            vo.setStatus(true);
                            JSONObject result = new JSONObject();
                            if (Build.VERSION.SDK_INT > 29) {
                                result.put("file_path", file.getName());
                            } else {
                                result.put("file_path", file.getAbsolutePath());
                            }
                            vo.setResult(result);
                            vo.setMessage("已成功下载至图库");
                            sendResponse(JSONObject.toJSONString(vo));
                            if (Build.VERSION.SDK_INT > 29) {
                                BitmapUtils.saveVideoToAlbumAfterQ(mContext, file.getAbsolutePath());
                            } else {
                                mediaReload(file);
                            }
                        }

                        @Override
                        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                        }

                        @Override
                        protected void error(BaseDownloadTask task, Throwable e) {
                            mLoading.dismiss();
                            vo.setStatus(false);
                            vo.setMessage("下载视频失败");
                            sendResponse(JSONObject.toJSONString(vo));
                        }

                        @Override
                        protected void warn(BaseDownloadTask task) {
                            mLoading.dismiss();
                        }
                    })
                    .start();
        }
    }

    /**
     * 调用提词器
     */
    private void showPrompt() {
        JSONObject params = jsData.getJSONObject("params");
        String content = params.getString("text");
        String mode = params.getString("mode");
        String direction = params.getString("direction");

        AppRespVo vo = new AppRespVo();
        vo.setAction(this.action);
        vo.setUser_data(jsData.getJSONObject("user_data"));

        if (content.isEmpty()) {
            vo.setMessage("提词器内容为空");
            vo.setStatus(false);
            sendResponse(JSONObject.toJSONString(vo));
            return;
        }

        if (mode.equals("subtitle")) { //字幕题词
            Intent intent = new Intent(mContext, FullScreenActivity.class);
            intent.putExtra("content", content);
            intent.putExtra("orientation", direction.equals("portrait") ? 0 : 1);
            mContext.startActivity(intent);

        } else if (mode.equals("float")) {
            MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_FLOAT_SETTING);
            JSONObject data = new JSONObject();
            data.put("data", jsData);
            msgEvent.setExtras(data);
            EventBus.getDefault().post(msgEvent);
        }

        vo.setStatus(true);
        vo.setMessage("调用提词器成功");
        sendResponse(JSONObject.toJSONString(vo));
    }

    /**
     * 获取剪切板内容
     */
    private void getClipboardText() {
        JSONObject params = jsData.getJSONObject("params");

        AppRespVo vo = new AppRespVo();
        vo.setAction(this.action);
        vo.setUser_data(jsData.getJSONObject("user_data"));

        String text = ClipboardUtils.getText(mContext);
        if (text == null || text.equals("")) {
            vo.setStatus(false);
            vo.setMessage("获取剪切板异常");
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data", text);
            vo.setStatus(true);
            vo.setMessage("获取成功");
            vo.setResult(jsonObject);
        }
        sendResponse(JSONObject.toJSONString(vo));
    }

    /**
     * 跳转浏览器
     */
    private void gotoBrowser() {
        MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_REQUEST_BROWSER);
        JSONObject data = new JSONObject();
        data.put("data", jsData);
        msgEvent.setExtras(data);
        EventBus.getDefault().post(msgEvent);
    }


    private void callPhone() {
        JSONObject params = jsData.getJSONObject("params");
        MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_CALL_PHONE);
        JSONObject data = new JSONObject();
        data.put("mobile", params.getString("mobile"));
        msgEvent.setExtras(data);
        EventBus.getDefault().post(msgEvent);
    }

    /**
     * 获取设备信息
     */
    @SuppressLint("HardwareIds")
    private void getDeviceInfo() {
        JSONObject result = new JSONObject();
        String deviceId = DeviceIdUtil.getDeviceId(mContext);
        if (StringUtils.isEmpty(deviceId)) {
            deviceId = JCoreHelper.getDeviceId(mContext);
        }
        result.put("device_id", deviceId);
        result.put("device_model", String.format("%s %s", Build.MANUFACTURER, Build.MODEL));
        result.put("os_version", Build.VERSION.RELEASE);
        result.put("app_platform", "Android");
        result.put("app_build", BuildConfig.VERSION_CODE);
        result.put("app_version", BuildConfig.VERSION_NAME);

        AppRespVo vo = new AppRespVo();
        vo.setAction(this.action);
        vo.setUser_data(jsData.getJSONObject("user_data"));
        vo.setStatus(true);
        vo.setResult(result);
        sendResponse(JSONObject.toJSONString(vo));
    }

    /**
     * 抖音
     */
    private void douyinAuth() {
        JSONObject params = jsData.getJSONObject("params");
        String scope = params.getString("scope");

        if (!DouYinUtils.isInstalled(mContext)) {
            showToast("该手机未检测到安装了抖音短视频App");
            return;
        }

        DouYinUtils utils = new DouYinUtils(mContext);
        utils.authorize(scope);

    }


    //抖音授权回调
    public void sendDyAuthResp(JSONObject data) {
        if (data.getIntValue("errorCode") == 0) {
            showToast("授权成功");
        } else {
            showToast(data.getString("errorMsg"));
        }
    }

    //快手分享
    private void openKuaiShou() {
        JSONObject params = jsData.getJSONObject("params");
        ClipboardUtils.setText(mContext, params.getString("text"));

        KuaiShouInfoVo vo = new KuaiShouInfoVo();
        vo.setTag(params.getString("tag"));
        vo.setVideo(params.getString("video"));
        vo.setUseImgs(params.getBooleanValue("use_imgs"));
        if (vo.isUseImgs()) {
            vo.setImgs(params.getJSONArray("base64_imgs"));
        } else {
            vo.setVideoNb(params.getString("video_nb"));
        }
        vo.setEdit_type(params.getString("edit_type"));

        KuaiShouUtils utils = new KuaiShouUtils(mContext);
        utils.share(vo);

    }


    //快手授权回调
    public void sendKSShareResp(JSONObject data) {
        if (data.getIntValue("errorCode") == 1) {
            showToast("分享成功");
        } else {
            showToast(data.getString("errorMsg"));
        }
    }

    //快手授权回调
    public void sendXIAOHONGSHUShareResp(JSONObject data) {
        if (data.getIntValue("errorCode") == 1998) {
            showToast("小红书分享成功");
        } else {
            showToast(data.getString("errorMsg"));
        }
    }

    //扫码结果回调
    public void sendScanCodeResp(JSONObject data) {
        JSONObject userData = jsData.getJSONObject("user_data");
        AppRespVo vo = new AppRespVo();
        vo.setAction(action);
        vo.setUser_data(userData);
        vo.setStatus(true);
        vo.setMessage("扫码成功");
        vo.setResult(data);
        sendResponse(JSONObject.toJSONString(vo));
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(NotificationManager manager, String channelId, String channelName, int importance) {
        manager.createNotificationChannel(new NotificationChannel(channelId, channelName, importance));
    }

    public void sendNotificationResp(String code) {
        AppRespVo vo = new AppRespVo();
        vo.setAction("custom_notice_receive");
        vo.setStatus(true);
        vo.setMessage("点击");
        JSONObject object = new JSONObject();
        object.put("data", code);
        vo.setResult(object);
        sendResponse(JSONObject.toJSONString(vo));
    }

    //调用震动
    private void vibrate() {
        JSONObject extras = new JSONObject();
        extras.put("data", jsData);
        MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_REQUEST_VIBRATOR);
        msgEvent.setExtras(extras);
        EventBus.getDefault().post(msgEvent);
    }


    //调用js
    public void sendResponse(String params) {
        Log.e("JS", String.format("WebView On Send Response: %s", params));
        if (webView == null) return;
        ((Activity) mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webView.evaluateJavascript("appResponse(\"" + HelperUtils.strToBase64(params) + "\")", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {

                    }
                });
            }
        });
    }

    //调用js
    public void sendResponse(String functionName, String params) {
        Log.e("JS", String.format("WebView On Send Response: %s", params));
        if (webView == null) return;
        ((Activity) mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webView.evaluateJavascript(functionName + "(" + params + ")", new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String value) {

                            }
                        }
                );
            }
        });
    }

    //检测是否可访问相机
    private void checkCanAccessCamera(BlockUtils block) {
        MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_REQUEST_CAMERA_PERMS);
        JSONObject data = new JSONObject();
        data.put("block", block);
        data.put("data", jsData);
        msgEvent.setExtras(data);
        EventBus.getDefault().post(msgEvent);
    }

    //视频选择
    private void videoPick(JSONObject jsData) {
        WebviewPickerUtils pick = new WebviewPickerUtils(mContext);
        pick.openVideoPickerNew(mContext, new OnVideoPickCallback() {
            @Override
            public void onPickCallback(File file) {
                // 消抖
                if (upVideoFlag) return;
                upVideoFlag = true;
                UpYunCompleteListener upYunCompleteListener = new UpYunCompleteListener() {
                    @Override
                    public void complete(@Nullable String url, UpYunEntity entity) {
                        JSONObject result = new JSONObject();
                        result.put("video_url", url);
                        AppRespVo vo = new AppRespVo();
                        vo.setAction("video_upload");
                        vo.setUser_data(jsData.getJSONObject("user_data"));
                        vo.setStatus(true);
                        vo.setResult(result);
                        sendResponse(JSONObject.toJSONString(vo));
                        upVideoFlag = false;
                    }

                    @Override
                    public void fail(@Nullable String errorStr) {
                        JSONObject userData = jsData.getJSONObject("user_data");
                        AppRespVo vo = new AppRespVo();
                        vo.setAction("video_upload");
                        vo.setUser_data(userData);
                        vo.setStatus(false);
                        if (action.equals("video_upload_cancel")) {
                            vo.setAction("video_upload_cancel");
                            errorStr = "用户主动取消上传";
                        }
                        vo.setMessage(errorStr);
                        sendResponse(JSONObject.toJSONString(vo));
                        upVideoFlag = false;
                    }

                    @Override
                    public void onProgress(int percent) {
                        Log.e("TAG", "进度为" + percent + "%");
                        JSONObject result = new JSONObject();
                        result.put("progress", percent);
                        AppRespVo vo = new AppRespVo();
                        vo.setAction("video_upload_progress");
                        vo.setStatus(true);
                        vo.setResult(result);
                        sendResponse(JSONObject.toJSONString(vo));
                    }
                };
                String city_key = "";
                if (jsData.getJSONObject("params").getString("city_key") != null) {
                    city_key = jsData.getJSONObject("params").getString("city_key");
                }
                String uid = "";
                if (jsData.getJSONObject("params").getInteger("uid") != null) {
                    uid = jsData.getJSONObject("params").getInteger("uid").toString();
                }
                if ("breakpoint".equals(uploadType)) {
                    upYunUtil.parallelUpload(mContext, file, city_key, uid, upYunCompleteListener);
                } else {
                    upYunUtil.formUpload(mContext, file, city_key, uid, upYunCompleteListener);
                }
            }

            @Override
            public void onPickFailCallback(String errorMsg) {
                JSONObject userData = jsData.getJSONObject("user_data");
                AppRespVo vo = new AppRespVo();
                vo.setAction(action);
                vo.setUser_data(userData);
                vo.setStatus(false);
                vo.setMessage(errorMsg);
                sendResponse(JSONObject.toJSONString(vo));
                upVideoFlag = false;
            }
        });
    }


    private void cancelVideoUpload() {
        if ("breakpoint".equals(uploadType)) {
            upYunUtil.uploadPause();
        } else {
            upYunUtil.formUploadCancel();
        }
    }

    private void startUrlVideo(String url) {
        // 创建一个Intent
        Intent intent = new Intent(mContext, VideoPalyActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("url", url);
        intent.putExtras(bundle);
        // 启动Intent
        mContext.startActivity(intent);
    }

    public static File getFile(String fileName) {
        String appName = MyApplication.getInstance().getString(R.string.app_name);
        String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + appName;
        if (Build.VERSION.SDK_INT > 29) {
            dir = MyApplication.getInstance().getExternalFilesDir(null).getAbsolutePath() + File.separator + appName;
        }
        isExist(dir);
        return new File(dir, fileName);
    }

    //刷新媒体库
    private void mediaReload(File file) {
        MediaScannerConnection.scanFile(mContext, new String[]{file.toString()}, new String[]{file.getName()}, null);
    }

}
